<template>
  <div class="user-management">
    <t-card title="用户管理">
      <template #actions>
        <t-button theme="primary" @click="showCreateDialog = true">
          <template #icon>
            <t-icon name="add" />
          </template>
          新建用户
        </t-button>
      </template>

      <t-table
        :data="users"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        @page-change="onPageChange"
      >
        <template #op="slotProps">
          <t-space>
            <t-button theme="primary" variant="text" @click="handleEdit(slotProps.row)">
              编辑
            </t-button>
            <t-button theme="danger" variant="text" @click="handleDelete(slotProps.row)">
              删除
            </t-button>
          </t-space>
        </template>
      </t-table>
    </t-card>

    <!-- 创建用户对话框 -->
    <t-dialog
      v-model:visible="showCreateDialog"
      header="创建用户"
      :confirm-on-enter="true"
      @confirm="handleCreateConfirm"
    >
      <t-form ref="form" :data="formData" :rules="rules">
        <t-form-item label="用户名" name="username">
          <t-input v-model="formData.username" placeholder="请输入用户名" />
        </t-form-item>
        <t-form-item label="邮箱" name="email">
          <t-input v-model="formData.email" placeholder="请输入邮箱" />
        </t-form-item>
        <t-form-item label="密码" name="password">
          <t-input v-model="formData.password" type="password" placeholder="请输入密码" />
        </t-form-item>
      </t-form>
    </t-dialog>

    <!-- 编辑用户对话框 -->
    <t-dialog
      v-model:visible="showEditDialog"
      header="编辑用户"
      :confirm-on-enter="true"
      @confirm="handleEditConfirm"
    >
      <t-form ref="editForm" :data="editFormData" :rules="editRules">
        <t-form-item label="用户名" name="username">
          <t-input v-model="editFormData.username" placeholder="请输入用户名" />
        </t-form-item>
        <t-form-item label="邮箱" name="email">
          <t-input v-model="editFormData.email" placeholder="请输入邮箱" />
        </t-form-item>
        <t-form-item label="密码" name="password">
          <t-input v-model="editFormData.password" type="password" placeholder="留空表示不修改密码" />
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
import type { PaginationProps, FormInstanceFunctions } from 'tdesign-vue-next'
import { userApi, type User } from '@/services/api'

// 表格列配置
const columns = [
  { colKey: 'id', title: 'ID', width: 100 },
  { colKey: 'username', title: '用户名' },
  { colKey: 'email', title: '邮箱' },
  { colKey: 'created_at', title: '创建时间' },
  { colKey: 'op', title: '操作', width: 200 }
]

// 数据和加载状态
const users = ref<User[]>([])
const loading = ref(false)
const pagination = ref<PaginationProps>({
  total: 0,
  pageSize: 10,
  current: 1
})

// 创建表单相关
const form = ref<FormInstanceFunctions>()
const showCreateDialog = ref(false)
const formData = ref({
  username: '',
  email: '',
  password: ''
})
const rules = {
  username: [{ required: true, message: '请输入用户名', type: 'error' }],
  email: [
    { required: true, message: '请输入邮箱', type: 'error' },
    { pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/, message: '请输入正确的邮箱格式', type: 'error' }
  ],
  password: [{ required: true, message: '请输入密码', type: 'error' }]
}

// 编辑表单相关
const editForm = ref<FormInstanceFunctions>()
const showEditDialog = ref(false)
const currentEditingId = ref<number>()
const editFormData = ref({
  username: '',
  email: '',
  password: ''
})
const editRules = {
  username: [{ required: true, message: '请输入用户名', type: 'error' }],
  email: [
    { required: true, message: '请输入邮箱', type: 'error' },
    { pattern: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/, message: '请输入正确的邮箱格式', type: 'error' }
  ]
}

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true
  try {
    const data = await userApi.getUsers()
    users.value = data
    pagination.value.total = data.length
  } catch (error) {
    MessagePlugin.error('获取用户列表失败')
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 页码改变
const onPageChange = (current: number) => {
  pagination.value.current = current
  fetchUsers()
}

// 编辑用户
const handleEdit = (user: User) => {
  currentEditingId.value = user.id
  editFormData.value = {
    username: user.username,
    email: user.email,
    password: ''
  }
  showEditDialog.value = true
}

// 确认编辑
const handleEditConfirm = async () => {
  if (!currentEditingId.value) return
  
  try {
    const valid = await editForm.value?.validate()
    if (!valid) return

    const updateData: any = {}
    updateData.username = editFormData.value.username
    updateData.email = editFormData.value.email
    if (editFormData.value.password) {
      updateData.password = editFormData.value.password
    }

    await userApi.updateUser(currentEditingId.value, updateData)
    MessagePlugin.success('更新用户成功')
    showEditDialog.value = false
    fetchUsers()
  } catch (error) {
    MessagePlugin.error('更新用户失败')
    console.error('更新用户失败:', error)
  }
}

// 删除用户
const handleDelete = async (user: User) => {
  const dialog = DialogPlugin.confirm({
    header: '确认删除',
    body: `确定要删除用户 "${user.username}" 吗？`,
    confirmBtn: {
      content: '删除',
      theme: 'danger'
    },
    cancelBtn: '取消',
    closeOnEscKeydown: true,
    closeOnOverlayClick: true,
    onConfirm: async () => {
      try {
        await userApi.deleteUser(user.id)
        MessagePlugin.success('删除用户成功')
        fetchUsers()
      } catch (error) {
        MessagePlugin.error('删除用户失败')
        console.error('删除用户失败:', error)
      } finally {
        dialog.destroy()
      }
    },
    onClose: () => {
      dialog.destroy()
    }
  })
}

// 创建用户
const handleCreateConfirm = async () => {
  try {
    const valid = await form.value?.validate()
    if (!valid) return

    await userApi.createUser(formData.value)
    MessagePlugin.success('创建用户成功')
    showCreateDialog.value = false
    formData.value = { username: '', email: '', password: '' }
    fetchUsers()
  } catch (error) {
    MessagePlugin.error('创建用户失败')
    console.error('创建用户失败:', error)
  }
}

// 初始化
onMounted(() => {
  fetchUsers()
})
</script>

<style>
.user-management {
  padding: 16px;
}
</style>
